<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="600px" :title="drawerTitle">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="work-order-form">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="工单编码" prop="workOrderCode">
            <el-input v-model="formData.workOrderCode" placeholder="请输入工单编码" clearable :disabled="isEdit" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="工单类型" prop="workOrderType">
            <el-select
              v-model="formData.workOrderType"
              placeholder="请选择工单类型"
              clearable
              style="width: 100%"
              :disabled="isEdit || isReworkMode"
            >
              <el-option v-for="type in workOrderTypeOptions" :key="type.value" :label="type.label" :value="type.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 返工工单的原工单信息 -->
      <el-row :gutter="20" v-if="isReworkOrder">
        <el-col :span="24">
          <el-form-item label="原工单" prop="originalWorkOrderId">
            <el-input v-model="originalWorkOrderDisplay" placeholder="原工单信息" readonly style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="产品" prop="productId">
            <el-select v-model="formData.productId" placeholder="请选择产品" clearable filterable style="width: 100%">
              <el-option v-for="product in productOptions" :key="product.id" :label="product.name" :value="product.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="工艺路线" prop="routeId">
            <el-select v-model="formData.routeId" placeholder="请选择工艺路线" clearable filterable style="width: 100%">
              <el-option v-for="route in routeOptions" :key="route.id" :label="route.name" :value="route.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="产线" prop="productionLineId">
            <el-select v-model="formData.productionLineId" placeholder="请选择产线" clearable filterable style="width: 100%">
              <el-option v-for="line in productionLineOptions" :key="line.id" :label="line.name" :value="line.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="计划数量" prop="plannedQuantity">
            <el-input-number
              v-model="formData.plannedQuantity"
              :min="1"
              :max="999999"
              placeholder="请输入计划数量"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 计划时间范围 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="计划时间" prop="plannedTimeRange">
            <el-date-picker
              v-model="plannedTimeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="计划开始时间"
              end-placeholder="计划结束时间"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleTimeRangeChange"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 备注 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="formData.remarks"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>


      <el-row :gutter="20" v-if="isEdit && formData.completedQuantity">
        <el-col :span="24">
          <el-form-item label="完成数量">
            <span>{{ formData.completedQuantity }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
        {{ isEdit ? "更新" : "创建" }}
      </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="workOrderForm">
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, type FormInstance } from "element-plus";
import {
  createWorkOrder,
  getWorkOrderById,
  updateWorkOrder,
  type WorkOrder,
  getSuggestedWorkOrderCode
} from "@/api/modules/workorder";
import { getProductOptions } from "@/api/modules/material";
import { getRouteOptions } from "@/api/modules/route";
import { getProductionLineOptions } from "@/api/modules/productionLine";

// 抽屉参数接口
interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<WorkOrder.WorkOrderListItem>;
  getTableList?: () => void;
}

const route = useRoute();
const formRef = ref<FormInstance>();
const submitLoading = ref(false);
const drawerVisible = ref(false);

// 抽屉属性
const drawerProps = ref<DrawerProps>({
  title: "",
  isView: false,
  row: {}
});

// 判断是否为编辑模式
const isEdit = computed(() => drawerProps.value.title === "编辑");

// 判断是否为返工模式（从URL参数获取）
const isReworkMode = computed(() => route.query.type === "rework");

// 判断是否为返工工单
const isReworkOrder = computed(() => formData.workOrderType === "rework");

// 抽屉标题
const drawerTitle = computed(() => {
  if (isReworkMode.value) return "创建返工工单";
  return `${drawerProps.value.title}工单`;
});

// 原工单显示信息
const originalWorkOrderDisplay = computed(() => {
  if (formData.originalWorkOrderId && formData.originalWorkOrderCode) {
    return `${formData.originalWorkOrderCode} (ID: ${formData.originalWorkOrderId})`;
  }
  return formData.originalWorkOrderId || "";
});

// 表单数据
const formData = reactive<Partial<WorkOrder.WorkOrderListItem>>({
  id: undefined,
  workOrderCode: "",
  productId: undefined,
  plannedQuantity: undefined,
  routeId: undefined,
  productionLineId: undefined,
  workOrderType: undefined,
  originalWorkOrderId: undefined,
  originalWorkOrderCode: undefined,
  plannedStartTime: undefined,
  plannedEndTime: undefined,
  remarks: undefined,
  status: "",
  completedQuantity: undefined
});

// 计划时间范围（用于时间范围选择器）
const plannedTimeRange = ref<[string, string] | null>(null);

// 选项数据
const productOptions = ref<Array<{ id: string; name: string }>>([]);
const routeOptions = ref<Array<{ id: string; name: string }>>([]);
const productionLineOptions = ref<Array<{ id: string; name: string }>>([]);

// 工单类型选项
const workOrderTypeOptions = ref([
  { value: "production", label: "标准生产工单" },
  { value: "rework", label: "返工工单" },
  { value: "trial", label: "试产工单" },
  { value: "outsourcing", label: "外协工单" },
  { value: "maintenance", label: "维修工单" },
  { value: "sample", label: "样品工单" },
  { value: "engineering_change", label: "工程变更工单" }
]);

// 表单验证规则
const rules = reactive({
  workOrderCode: [
    { required: true, message: "请输入工单编码", trigger: "blur" },
    {
      pattern: /^WO-\d{8}-\d{3}$/,
      message: "工单编码格式错误，必须符合格式 WO-YYYYMMDD-NNN",
      trigger: "blur"
    }
  ],
  workOrderType: [{ required: true, message: "请选择工单类型", trigger: "change" }],
  productId: [{ required: true, message: "请选择产品", trigger: "change" }],
  plannedQuantity: [{ required: true, message: "请输入计划数量", trigger: "blur" }],
  routeId: [{ required: true, message: "请选择工艺路线", trigger: "change" }],
  productionLineId: [{ required: true, message: "请选择产线", trigger: "change" }],
  originalWorkOrderId: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (formData.workOrderType === "rework" && !value) {
          callback(new Error("返工工单必须指定原工单"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  plannedTimeRange: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value && Array.isArray(value) && value.length === 2) {
          const [startTime, endTime] = value;
          if (new Date(endTime) <= new Date(startTime)) {
            callback(new Error("计划结束时间必须晚于计划开始时间"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ]
});

// 获取状态类型
const getStatusType = (status: string | undefined): "success" | "primary" | "warning" | "info" | "danger" => {
  if (!status) return "info";
  const statusMap: Record<string, "success" | "primary" | "warning" | "info" | "danger"> = {
    CREATED: "info",
    READY: "success",
    RELEASED: "warning",
    STARTED: "primary",
    SUSPENDED: "warning",
    COMPLETED: "success",
    CLOSED: "info",
    CANCELLED: "danger"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string | undefined): string => {
  if (!status) return "";
  const statusMap: Record<string, string> = {
    CREATED: "已创建",
    READY: "准备完成",
    RELEASED: "已下达",
    STARTED: "生产中",
    SUSPENDED: "已暂停",
    COMPLETED: "已完成",
    CLOSED: "已关闭",
    CANCELLED: "已取消"
  };
  return statusMap[status] || status;
};

// 获取工单详情
const getWorkOrderDetail = async (id: string) => {
  try {
    const res = await getWorkOrderById(id);
    Object.assign(formData, res.data);
  } catch (error) {
    console.error("获取工单详情失败:", error);
    ElMessage.error("获取工单详情失败");
  }
};

// 获取建议的工单编码
const getSuggestedCode = async () => {
  try {
    const res = await getSuggestedWorkOrderCode();
    return res.data;
  } catch (error) {
    console.error("获取建议工单编码失败:", error);
    return "";
  }
};

// 加载选项数据
const loadOptions = async () => {
  try {
    console.log("开始加载选项数据...");
    const [products, routes, lines] = await Promise.all([getProductOptions(), getRouteOptions(), getProductionLineOptions()]);
    
    console.log("API响应数据:", { products, routes, lines });
    
    productOptions.value = products.data || [];
    routeOptions.value = routes.data || [];
    productionLineOptions.value = lines.data || [];
    
    console.log("选项数据加载完成:", {
      products: productOptions.value.length,
      routes: routeOptions.value.length,
      lines: productionLineOptions.value.length
    });
    
    console.log("具体选项数据:", {
      productOptions: productOptions.value,
      routeOptions: routeOptions.value,
      productionLineOptions: productionLineOptions.value
    });
  } catch (error) {
    console.error("加载选项数据失败:", error);
    ElMessage.error("加载选项数据失败");
  }
};

// 重置表单数据
const resetFormData = async () => {
  const suggestedCode = await getSuggestedCode();
  Object.assign(formData, {
    id: undefined,
    workOrderCode: suggestedCode,
    productId: undefined,
    plannedQuantity: undefined,
    routeId: undefined,
    productionLineId: undefined,
    workOrderType: isReworkMode.value ? "rework" : "production",
    originalWorkOrderId: undefined,
    originalWorkOrderCode: undefined,
    plannedStartTime: undefined,
    plannedEndTime: undefined,
    remarks: undefined,
    status: "",
    completedQuantity: undefined
  });

  // 重置时间范围选择器
  plannedTimeRange.value = null;

  // 如果是返工模式，从URL参数获取原工单信息
  if (isReworkMode.value && route.query.originalId) {
    formData.originalWorkOrderId = route.query.originalId as string;
    // TODO: 根据原工单ID获取原工单信息
    await loadOriginalWorkOrderInfo(formData.originalWorkOrderId);
  }
};

// 接收父组件传过来的参数
const open = async (params: DrawerProps) => {
  drawerProps.value = params;

  // 每次打开表单时都加载选项数据
  await loadOptions();

  if (params.title === "编辑" || params.title === "查看") {
    // 编辑和查看模式，直接使用传入的数据
    Object.assign(formData, params.row);
  } else {
    // 新增模式，重置表单并获取建议编码
    await resetFormData();
  }

  drawerVisible.value = true;
};

// 加载原工单信息
const loadOriginalWorkOrderInfo = async (originalId: string) => {
  try {
    const res = await getWorkOrderById(originalId);
    const originalWorkOrder = res.data;
    formData.originalWorkOrderCode = originalWorkOrder.workOrderCode;
    // 可以预填充一些信息，比如产品ID
    if (!formData.productId) {
      formData.productId = originalWorkOrder.productId;
    }
  } catch (error) {
    console.error("获取原工单信息失败:", error);
    ElMessage.warning("获取原工单信息失败");
  }
};

// 提交表单
const handleSubmit = () => {
  if (drawerProps.value.isView) return;

  formRef.value?.validate(async valid => {
    if (!valid) return;

    submitLoading.value = true;
    try {
      if (isEdit.value && formData.id) {
        // 编辑模式 - 调用更新接口
        const params: WorkOrder.CreateWorkOrderRequest = {
          workOrderCode: formData.workOrderCode!,
          productId: formData.productId!,
          plannedQuantity: formData.plannedQuantity!,
          routeId: formData.routeId,
          productionLineId: formData.productionLineId,
          workOrderType: formData.workOrderType!,
          originalWorkOrderId: formData.originalWorkOrderId,
          plannedStartTime: formData.plannedStartTime as string,
          plannedEndTime: formData.plannedEndTime as string,
          remarks: formData.remarks
        };
        await updateWorkOrder(formData.id, params);
        ElMessage.success("工单更新成功");
      } else {
        // 新增模式
        const params: WorkOrder.CreateWorkOrderRequest = {
          workOrderCode: formData.workOrderCode!,
          productId: formData.productId!,
          plannedQuantity: formData.plannedQuantity!,
          routeId: formData.routeId!,  // 确保必填字段不为空
          productionLineId: formData.productionLineId!,  // 确保必填字段不为空
          workOrderType: formData.workOrderType!,
          originalWorkOrderId: formData.originalWorkOrderId,
          plannedStartTime: formData.plannedStartTime as string,
          plannedEndTime: formData.plannedEndTime as string,
          remarks: formData.remarks
        };
        
        console.log('发送的工单创建参数:', params);
        console.log('表单数据:', formData);
        
        // 验证必填字段
        if (!params.productId) {
          ElMessage.error('请选择产品');
          return;
        }
        if (!params.routeId) {
          ElMessage.error('请选择工艺路线');
          return;
        }
        if (!params.productionLineId) {
          ElMessage.error('请选择产线');
          return;
        }
        
        await createWorkOrder(params);
        ElMessage.success(isReworkMode.value ? "返工工单创建成功" : "工单创建成功");
      }

      // 刷新父组件列表
      drawerProps.value.getTableList?.();
      drawerVisible.value = false;
    } catch (error: any) {
      console.error("操作失败:", error);
      console.error("错误响应:", error.response);
      
      let errorMessage = isEdit.value ? "工单更新失败" : "工单创建失败";
      
      if (error.response && error.response.data) {
        console.error("后端错误详情:", error.response.data);
        if (error.response.data.message) {
          errorMessage += ": " + error.response.data.message;
        } else if (error.response.data.msg) {
          errorMessage += ": " + error.response.data.msg;
        }
      }
      
      ElMessage.error(errorMessage);
    } finally {
      submitLoading.value = false;
    }
  });
};

// 处理时间范围变化
const handleTimeRangeChange = (value: [string, string] | null) => {
  if (value && Array.isArray(value) && value.length === 2) {
    formData.plannedStartTime = value[0];
    formData.plannedEndTime = value[1];
  } else {
    formData.plannedStartTime = undefined;
    formData.plannedEndTime = undefined;
  }
};

// 监听工单类型变化
watch(
  () => formData.workOrderType,
  newType => {
    if (newType !== "rework") {
      formData.originalWorkOrderId = undefined;
      formData.originalWorkOrderCode = undefined;
    }
  }
);

// 监听表单数据中的时间变化，同步到时间范围选择器
watch([() => formData.plannedStartTime, () => formData.plannedEndTime], ([startTime, endTime]) => {
  if (startTime && endTime) {
    plannedTimeRange.value = [startTime, endTime];
  } else {
    plannedTimeRange.value = null;
  }
});

// 取消操作
const handleCancel = () => {
  drawerVisible.value = false;
};

// 组件挂载时加载选项数据
onMounted(() => {
  loadOptions();
});

// 暴露方法给父组件
defineExpose({
  open
});
</script>

<style scoped>
.content-box {
  padding: 20px;
}

.form-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.form-header h2 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 500;
}

.work-order-form {
  max-width: 800px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>